package com.cloud.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
//@Component
public class PreFilter extends ZuulFilter {
    /**
     * 执行时机
     * pre:     在进入微服网关之间执行
     * route:   在执行微服务网关时执行
     * post:    在执行微服务网关之后执行
     * error:   在执行微服务出错执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 执行顺序
     * 数字越大,优先级越低
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否执行该过滤器
     * true:执行
     * false:不执行
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器执行逻辑
     *
     * @return 访问对应的微服务
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("PreFilter...." + System.currentTimeMillis());

        // Zuul网关提供的上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        HttpServletResponse response = context.getResponse();

        // 获取提交的token
        String token = request.getParameter("token");

        response.setContentType("application/json;charset=utf8");
        if(!"1".equals(token)){

            // 终止请求
            context.setSendZuulResponse(false);

            HashMap jsonMap = new HashMap() {{
                put("flag", true);
                put("statusCode", "500");
                put("message","权限不足");
            }};

            // 设置响应体
            try {
                context.setResponseBody(new ObjectMapper().writeValueAsString(jsonMap));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            // return方法,为了防止代码往下执行,返回值随意
            return 11;
        }

        return null;
    }
}
